﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using dreamwork.auth.api.Infrastructure;
using dreamwork.auth.api.Model.Data;
using DreamWork.Web.API.Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Reflection;

namespace dreamwork.auth.api
{
	public class Startup
	{
		public Startup(IConfiguration configuration)
		{
			Configuration = configuration;
		}

		public IConfiguration Configuration { get; }

		// This method gets called by the runtime. Use this method to add services to the container.
		public IServiceProvider ConfigureServices(IServiceCollection services)
		{

			#region Add SqlDB
			services.AddDbContext<SqlServerDBContext>(options =>
			{
				options.UseSqlServer(Configuration["SqlServer:ConnectionString"],  sqlOptions =>
				{
					//sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
					sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30),errorNumbersToAdd:null);
				});
			});
            #endregion

            services.AddTransient<ILoginService<ApplicationUser>, EFLoginService>();
			#region MongoDB
			/*
			services.AddTransient<IApplicationUserRepository, ApplicationUserSqlServerRepository>();
			services.AddTransient<ILoginService<ApplicationUser>, EFLoginService>();
			*/
			#endregion

			#region Add AspNet Identity
			services.AddIdentity<ApplicationUser, IdentityRole>(options =>
			{
				options.Password.RequireDigit = false;
				options.Password.RequireLowercase = false;
				options.Password.RequireUppercase = false;
				options.Password.RequireNonAlphanumeric = false;
				options.Password.RequiredUniqueChars = 0;
				options.Password.RequiredLength = 1;
			})
		  .AddEntityFrameworkStores<SqlServerDBContext>()
		  .AddDefaultTokenProviders();
			#endregion

			#region Add IdentityServer4
			services.AddIdentityServer(options =>
			{
				options.Authentication.CookieLifetime = TimeSpan.FromHours(1);
			})
			.AddDeveloperSigningCredential()
			.AddAspNetIdentity<ApplicationUser>()
			.AddInMemoryIdentityResources(Config.GetIdentityResources())
			.AddInMemoryApiResources(Config.GetApiResources())
			.AddInMemoryClients(Config.GetClients(Configuration));
			#endregion

			services.AddMvc()
			.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
			.AddControllersAsServices();

			#region Swagger
			services.AddSwaggerGen(options =>
			{
				options.DescribeAllEnumsAsStrings();
				options.SwaggerDoc("v1", new Info { Title = "Dreamwork Auth API", Version = "v1" });
				options.OperationFilter<HttpAuthHeaderFilter>();
			});
			#endregion

			#region Cors
			services.AddCors(options =>
			{
				options.AddPolicy("CorsPolicy",
					builder => builder.AllowAnyOrigin()
					.AllowAnyMethod()
					.AllowAnyHeader()
					.AllowCredentials());
			});
			#endregion

			var container = new ContainerBuilder();
			container.Populate(services);
			return new AutofacServiceProvider(container.Build());
		}

		// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
		public void Configure(IApplicationBuilder app, IHostingEnvironment env)
		{
			if (env.IsDevelopment())
			{
				app.UseDeveloperExceptionPage();
			}
			else
			{
				app.UseHsts();
			}

			app.UseHttpsRedirection();
			app.UseIdentityServer();
			app.UseStaticFiles();
			app.UseMvcWithDefaultRoute();

			app.UseSwagger()
		   .UseSwaggerUI(c =>
		   {
			   c.SwaggerEndpoint("/swagger/v1/swagger.json", "Dreamwork.Auth.API");
		   });
		}
	}
}
